package com.paradox.aggregation.provider.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;

public class ServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channels=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel ch=ctx.channel();
        channels.add(ch);
        channels.writeAndFlush("[客户端]("+ch.remoteAddress()+")上线了！\n");
        System.out.println("[客户端]("+ch.remoteAddress()+")上线了！\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        channels.forEach(ch -> {
            if(ch!=channelHandlerContext.channel()){
                ch.writeAndFlush("[客户端]("+ch.remoteAddress()+"):"+s+"\n");
            }else{
                ch.writeAndFlush("[客户端](我):"+s+"\n");
            }
        });
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel ch=ctx.channel();
        channels.remove(ch);
        channels.writeAndFlush("[客户端]("+ch.remoteAddress()+")下线了！\n");
        System.out.println("[客户端]("+ch.remoteAddress()+")下线了！\n");
    }
}
